﻿using System;
using System.Collections.Generic;
using FiddlerFirePHPInspector.BusinessObjects.FirePHP;
using FiddlerFirePHPInspector.BusinessObjects.Wildfire;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace FiddlerFirePHPInspector.Processors
{
    public static class FirePHPProcessor
    {
        private const string FirePHPFirebugConsoleStructure = "http://meta.firephp.org/Wildfire/Structure/FirePHP/FirebugConsole/0.1";
        private const string JsonStreamProtocol = "http://meta.wildfirehq.org/Protocol/JsonStream/0.2";
        private const string FirePHPWildfirePlugin = "http://meta.firephp.org/Wildfire/Plugin/FirePHP/Library-FirePHPCore/0.3";

        public static bool IsWildfireDataFirePHP(WildfireData wildfireData)
        {
            return wildfireData.Protocol.Equals(JsonStreamProtocol)
                && wildfireData.Plugin.Equals(FirePHPWildfirePlugin)
                && wildfireData.Structure.Equals(FirePHPFirebugConsoleStructure);
        }

        public static List<FirePHPLog> ProcessFirePHPWildfireData(WildfireData wildfireData)
        {
            if (!IsWildfireDataFirePHP(wildfireData))
            {
                throw new ArgumentException("WildfireData is not FirePHP Data");
            }

            List<FirePHPLog> firePHPLogs = new List<FirePHPLog>();

            foreach (var payload in wildfireData.Payloads)
            {
                string[] splitWildfirePayload = payload.Payload.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                var payloadLength = int.Parse(splitWildfirePayload[0]);
                JArray payloadJson = (JArray)JsonConvert.DeserializeObject(splitWildfirePayload[1]);

                string logHeaderJson = payloadJson[0].ToString(Formatting.None, new JsonConverter[] { });
                string logBody = payloadJson[1].ToString(Formatting.None, new JsonConverter[] { });

                FirePHPLogHeader firePHPLogHeader = JsonConvert.DeserializeObject<FirePHPLogHeader>(logHeaderJson);

                FirePHPLog firePHPLog = new FirePHPLog { SequenceNumber = payload.SequenceNumber, FirePHPLogHeader = firePHPLogHeader, LogBody = logBody };
                firePHPLogs.Add(firePHPLog);
            }

            return firePHPLogs;
        }
    }
}
